#!/bin/bash

#
# bash script for playing first result of a query from youtube
# ### Pieter . Colpaert [aŧ] gmail . com (c) 2009 GPLv2+
# #### code.google.com/p/oywl
#

##########################################
#PART ZERO - CONFIG
##########################################

#extra mplayer arguments
mpargs="-ao sdl -cache 10000 -framedrop"

###########################################
#PART ONE - searching for a youtube video
###########################################
[[ $1 != "" ]] && {
    echo "#...Connecting to youtube search page for $1..."
    #this is needed because the url won't accept spaces
    set -- ${@//" "/+}
    #getting youtube searchpage
    wget "http://www.youtube.com/results?search_query=$1" --output-document=/tmp/oywl.html 2>/dev/null
    echo "#...ok - got the thing..."
    result=$(grep video-url /tmp/oywl.html -m 1)
    echo $result;
    result=$(perl -e "print \$1 if('$result'=~/video-url-(.{11})\"/)")
    echo $result
} || {
    echo "#...No videotopic specified. I will load the video about the Yorkshire men...\n";
}
#when no result found or no vars set, display the four yorkshire men
topic=${@-"The four yorkshire men"}
result=${result-"Xe1a1wHxTyo"};
###########################################
#PART TWO - getting the video url
###########################################
url="http://www.youtube.com/watch?v=$result"
echo "#...Getting the video file-url..."
wget "$url" --output-document=/tmp/oywl.html 2>/dev/null


#setting the topic title
title=$(grep VIDEO_TITLE /tmp/oywl.html)
title=$(perl -e "print \$1 if(\"$title\" =~ /VIDEO_TITLE': '(.*?)'/)")
echo $title;
#get some different quality url's
url=$(grep fmt_url_map /tmp/oywl.html)
url=${url:13:2000}
url=$( perl -e "print \$1 if('$url' =~ /.*?fmt_url_map\": \"(.*?)\", .*/);" )
#filter out hex - values in the urls
url=$(perl -e "\$url = '$url'; \$url =~ s/%([a-fA-F0-9]{2,2})/chr(hex(\$1))/eg;print \$url")
IFS="|"
declare -a Array=($url)
lowkwal=${Array[@]: -1}

##########################################
#PART THREE - playing the file
##########################################

echo "
We will play this video for you:
ID = $result
Topic = $topic
Videotitle = $title

Please feel free when the video is running to use mplayer command in this terminal
#... Buffering your video ...
"

mplayer $mpargs $lowkwal 2>/dev/null 1>/dev/null
echo "Thank you for using Oh You Were Lucky!"